<template>
  <div class="page">
    <div class="header-num">
      <div><span class="page-num">3</span><span class="page-title">现宅基地情况</span></div>
      <div class="plan">3/5</div>
    </div>
    <van-form ref="dataForm" label-width="45%">
      <div class="info-message">
        <div class="info-title">现宅基地及农房情况</div>
        <div class="info-form">
          <van-cell-group inset>
            <van-field
              v-model="form.homesteadArea"
              :rules="dataRule.homesteadArea"
              required
              label="宅基地面积"
              type="number"
              placeholder="宅基地面积"
            >
              <template #extra>
                <div>m<sup>2</sup></div>
              </template>
            </van-field>
            <van-field
              v-model="form.preCapitaHomesteadArea"
              :rules="dataRule.preCapitaHomesteadArea"
              required
              label="人均宅基地面积"
              type="number"
              placeholder="人均宅基地面积"
            >
              <template #extra>
                <div>m<sup>2</sup></div>
              </template>
            </van-field>
            <van-field v-model="form.certOwnershipNo1" :rules="dataRule.certOwnershipNo1" required label="权属证书号" placeholder="权属证书号">
            </van-field>
            <van-field
              v-model="form.constructionArea"
              :rules="dataRule.constructionArea"
              required
              label="建筑面积"
              type="number"
              placeholder="建筑面积"
            >
              <template #extra>
                <div>m<sup>2</sup></div>
              </template>
            </van-field>
            <van-field
              v-model="form.preCapitaConstructionArea"
              :rules="dataRule.preCapitaConstructionArea"
              required
              label="人均建筑面积"
              type="number"
              placeholder="人均建筑面积"
            >
              <template #extra>
                <div>m<sup>2</sup></div>
              </template>
            </van-field>
            <van-field v-model="form.certOwnershipNo2" :rules="dataRule.certOwnershipNo2" required label="权属证书号" placeholder="权属证书号">
            </van-field>
            <van-field label="现宅基地处置情况" required label-width="100%"></van-field>
            <van-field name="radio">
              <template #input>
                <van-radio-group v-model="form.presentHomesteadDisposalCase" :rules="dataRule.presentHomesteadDisposalCase" direction="horizontal">
                  <van-radio name="1">保留</van-radio>
                  <van-radio name="2">退还村集体</van-radio>
                  <van-radio name="3">其他</van-radio>
                </van-radio-group>
              </template>
            </van-field>
            <van-field
              v-if="+form.presentHomesteadDisposalCase === 1"
              v-model="form.keepArea"
              :rules="dataRule.keepArea"
              label="保留面积"
              type="number"
              placeholder="保留面积"
            >
              <template #extra>
                <div>m<sup>2</sup></div>
              </template>
            </van-field>
            <van-field
              v-if="+form.presentHomesteadDisposalCase === 3"
              v-model="form.otherDisposalCase"
              :rules="dataRule.otherDisposalCase"
              label="其他处置情况"
              placeholder="其他处置情况"
            >
            </van-field>
          </van-cell-group>
        </div>
      </div>
      <div class="info-message">
        <div class="info-title">拟申请宅基地及建房情况</div>
        <div class="info-form">
          <van-cell-group inset>
            <van-field
              v-model="fieldValue"
              :rules="dataRule.cascaderValue"
              required
              readonly
              is-link
              name="picker"
              label="拟建位置"
              placeholder="请选择所在地区"
              @click="showPicker = true"
            />
            <van-popup v-model:show="showPicker" position="bottom">
              <van-cascader
                v-model="cascaderValue"
                title="请选择所在地区"
                :options="cascadeOptions"
                :field-names="fieldNames"
                @close="showPicker = false"
                @change="onChange"
                @finish="onFinish"
              />
            </van-popup>
            <van-field
              v-model="form.proposedLocationAddress"
              :rules="dataRule.proposedLocationAddress"
              required
              label="拟建详细位置"
              placeholder="拟建详细位置"
            >
            </van-field>
            <van-field
              v-model="form.proposedHomesteadArea"
              :rules="dataRule.proposedHomesteadArea"
              required
              label="宅基地面积"
              type="number"
              placeholder="宅基地面积"
            >
              <template #extra>
                <div>m<sup>2</sup></div>
              </template>
            </van-field>
            <van-field v-model="form.proposedEastTo" :rules="dataRule.proposedEastTo" required label="东至" placeholder="东至"> </van-field>
            <van-field v-model="form.proposedWestTo" :rules="dataRule.proposedWestTo" required label="西至" placeholder="西至"> </van-field>
            <van-field v-model="form.proposedSouthTo" :rules="dataRule.proposedSouthTo" required label="南至" placeholder="南至"> </van-field>
            <van-field v-model="form.proposedNorthTo" :rules="dataRule.proposedNorthTo" required label="北至" placeholder="北至"> </van-field>
            <van-field
              v-model="form.proposedConstructionLandArea"
              :rules="dataRule.proposedConstructionLandArea"
              required
              label="建设用地面积"
              type="number"
              placeholder="建设用地面积"
            >
              <template #extra>
                <div>m<sup>2</sup></div>
              </template>
            </van-field>
            <van-field
              v-model="form.proposedUnusedArea"
              :rules="dataRule.proposedUnusedArea"
              required
              label="未利用地面积"
              type="number"
              placeholder="未利用地面积"
            >
              <template #extra>
                <div>m<sup>2</sup></div>
              </template>
            </van-field>
            <van-field
              v-model="form.proposedAgriculturalLandArea"
              :rules="dataRule.proposedAgriculturalLandArea"
              required
              label="农用地面积"
              type="number"
              placeholder="农用地面积"
            >
              <template #extra>
                <div>m<sup>2</sup></div>
              </template>
            </van-field>
            <van-field
              v-model="form.proposedArableLand"
              :rules="dataRule.proposedArableLand"
              required
              label="农用地的耕地面积"
              type="number"
              placeholder="农用地的耕地面积"
            >
              <template #extra>
                <div>m<sup>2</sup></div>
              </template>
            </van-field>
            <van-field
              v-model="form.proposedWoodlandArea"
              :rules="dataRule.proposedWoodlandArea"
              required
              label="农用地的林地面积"
              type="number"
              placeholder="农用地的林地面积"
            >
              <template #extra>
                <div>m<sup>2</sup></div>
              </template>
            </van-field>
            <van-field
              v-model="form.proposedConstructionArea"
              :rules="dataRule.proposedConstructionArea"
              required
              label="建筑面积"
              type="number"
              placeholder="建筑面积"
            >
              <template #extra>
                <div>m<sup>2</sup></div>
              </template>
            </van-field>
            <van-field
              v-model="form.proposedBuildingStorey"
              :rules="dataRule.proposedBuildingStorey"
              required
              label="建筑层数"
              type="digit"
              placeholder="建筑层数"
            >
            </van-field>
            <van-field
              v-model="form.proposedBuildingHeight"
              :rules="dataRule.proposedBuildingHeight"
              required
              label="建筑高度"
              type="number"
              placeholder="建筑高度"
            >
            </van-field>
            <van-field label="设计图纸" required readonly></van-field>
            <van-field name="radio">
              <template #input>
                <van-radio-group v-model="form.proposedDesignType" :rules="dataRule.proposedDesignType" direction="horizontal">
                  <van-radio name="1">委托设计</van-radio>
                  <van-radio name="2">选通用图</van-radio>
                </van-radio-group>
              </template>
            </van-field>

            <div class="content" v-if="form.proposedDesignType === '2'">
              <van-pull-refresh v-model="refreshing" @refresh="onRefresh" class="product-list-refresh">
                <van-list
                  v-model:loading="loading"
                  :finished="finished"
                  :finished-text="architecturalStyleList.length ? '没有更多了' : '暂无记录'"
                  @load="onLoad"
                  @offset="10"
                >
                  <template v-if="architecturalStyleList.length">
                    <van-radio-group v-model="form.architectureAtlasId">
                      <van-cell-group>
                        <van-cell v-for="(item, index) in architecturalStyleList" :key="index" clickable @click="handleSelect(item.id)">
                          <template #title>
                            <span class="custom-title" @click="handlePreview(item.imageList)">{{ item.name }}</span>
                            <van-tag v-if="item.imageList" type="success" class="img-num">图片数量：{{ item.imageList.length }}</van-tag>
                          </template>
                          <template #right-icon>
                            <van-radio :name="item.id" />
                          </template>
                        </van-cell>
                      </van-cell-group>
                    </van-radio-group>
                  </template>
                  <van-skeleton v-else title :row="1"> </van-skeleton>
                </van-list>
              </van-pull-refresh>
            </div>

            <van-field label="是否征求相邻权利人意见" required label-width="100%"></van-field>
            <van-field name="radio">
              <template #input>
                <van-radio-group v-model="form.isSeekNeighboursOpinion" direction="horizontal" :rules="dataRule.isSeekNeighboursOpinion">
                  <van-radio :name="true">是</van-radio>
                  <van-radio :name="false">否</van-radio>
                </van-radio-group>
              </template>
            </van-field>
            <van-field
              v-if="form.isSeekNeighboursOpinion"
              v-model="form.neighboursOpinion"
              :rules="dataRule.neighboursOpinion"
              label="相邻权利人意见"
              placeholder="相邻权利人意见"
            >
            </van-field>
          </van-cell-group>
        </div>
      </div>
    </van-form>

    <div class="btn-group">
      <van-button type="button" class="cus-btn btn-default" @click="goBack">上一步</van-button>
      <van-button :loading="isCommit" type="button" class="cus-btn btn-default" @click="onSubmit">保存</van-button>
      <van-button type="button" class="cus-btn btn-primary" @click="goNext">下一步</van-button>
    </div>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs, ref, getCurrentInstance, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { Toast, ImagePreview } from 'vant'
import { findByParentCode } from '@/service/home'
import { architectureAtlas, saveBuildApply } from '@/service/build-apply'
export default {
  setup() {
    const router = useRouter()
    const store = useStore()
    const dataForm = ref(null)
    const fieldValue = ref('')
    const options = [
      {
        text: '棠口镇',
        value: '350923104',
        children: [
          { text: '棠口村民委员会', value: '350923104201' },
          { text: '孔源村民委员会', value: '350923104202' },
          { text: '山棠村民委员会', value: '350923104203' },
          { text: '龙源村民委员会', value: '350923104204' },
          { text: '安溪村民委员会', value: '350923104205' },
        ],
      },
    ]
    const form = reactive({
      presentHomesteadDisposalCase: '1',
      proposedDesignType: '1',
      isSeekNeighboursOpinion: true,
    })
    const state = reactive({
      isCommit: false,
      homesteadForm: {},
      radio: '',
      architecturalStyleList: [],
      showImg: false,
      previewImgs: [],
      loading: false,
      listQuery: { pageNo: 1, pageSize: 5 },
      cascaderValue: '',
      showPicker: false,
      fieldNames: { text: 'regionName', value: 'regionCode' },
      totalPage: 0,
      refreshing: false,
      finished: false,
      dataRule: {
        homesteadArea: [{ required: true, message: '请输入宅基地面积', trigger: 'onBlur' }],
        preCapitaHomesteadArea: [{ required: true, message: '请输入人均宅基地面积', trigger: 'onBlur' }],
        constructionArea: [{ required: true, message: '请输入建筑面积', trigger: 'onBlur' }],
        preCapitaConstructionArea: [{ required: true, message: '请输入人均建筑面积', trigger: 'onBlur' }],
        certOwnershipNo1: [{ required: true, message: '请输入权属证书号', trigger: 'onBlur' }],
        certOwnershipNo2: [{ required: true, message: '请输入权属证书号', trigger: 'onBlur' }],
        presentHomesteadDisposalCase: [{ required: true, message: '请选择现宅基地处置情况', trigger: 'onChange' }],
        keepArea: [{ required: true, message: '请输入保留面积', trigger: 'onBlur' }],
        otherDisposalCase: [{ required: true, message: '请输入其他处置情况', trigger: 'onBlur' }],
        cascaderValue: [{ required: true, message: '请选择拟建位置', trigger: 'onChange' }],
        proposedHomesteadArea: [{ required: true, message: '请输入宅基地面积', trigger: 'onBlur' }],
        proposedEastTo: [{ required: true, message: '请输入东至', trigger: 'onBlur' }],
        proposedWestTo: [{ required: true, message: '请输入西至', trigger: 'onBlur' }],
        proposedSouthTo: [{ required: true, message: '请输入南至', trigger: 'onBlur' }],
        proposedNorthTo: [{ required: true, message: '请输入北至', trigger: 'onBlur' }],
        proposedConstructionLandArea: [{ required: true, message: '请输入建设用地面积', trigger: 'onBlur' }],
        proposedUnusedArea: [{ required: true, message: '请输入未利用地面积', trigger: 'onBlur' }],
        proposedAgriculturalLandArea: [{ required: true, message: '请输入农用地面积', trigger: 'onBlur' }],
        proposedArableLand: [{ required: true, message: '请输入农用地的耕地面积', trigger: 'onBlur' }],
        proposedWoodlandArea: [{ required: true, message: '请输入农用地的林地面积', trigger: 'onBlur' }],
        proposedConstructionArea: [{ required: true, message: '请输入建筑面积', trigger: 'onBlur' }],
        proposedBuildingStorey: [{ required: true, message: '请输入建筑层数', trigger: 'onBlur' }],
        proposedBuildingHeight: [{ required: true, message: '请输入建筑高度', trigger: 'onBlur' }],
        proposedDesignType: [{ required: true, message: '请选择设计图纸', trigger: 'onChange' }],
        isSeekNeighboursOpinion: [{ required: true, trigger: 'onChange', message: '请选择是否征求相邻权利人意见' }],
        neighboursOpinion: [{ required: true, message: '请输入相邻权利人意见', trigger: 'onBlur' }],
        proposedLocationAddress: [{ required: true, message: '请输入拟建详细位置', trigger: 'onBlur' }],
      },
    })

    // 获取字典数据
    store.dispatch('getTownOptions')
    store.dispatch('getFileServerPrefix')

    // 全局属性
    const { $localStorage } = getCurrentInstance().appContext.config.globalProperties

    onMounted(() => {
      init()
    })
    const init = async () => {
      state.homesteadForm = JSON.parse($localStorage.get('homesteadForm'))
      if (state.homesteadForm && Object.keys(state.homesteadForm).length > 0) {
        form.homesteadArea = state.homesteadForm.homesteadArea
        form.preCapitaHomesteadArea = state.homesteadForm.preCapitaHomesteadArea
        form.certOwnershipNo1 = state.homesteadForm.certOwnershipNo1
        form.constructionArea = state.homesteadForm.constructionArea
        form.preCapitaConstructionArea = state.homesteadForm.preCapitaConstructionArea
        form.certOwnershipNo2 = state.homesteadForm.certOwnershipNo2
        form.presentHomesteadDisposalCase = state.homesteadForm.presentHomesteadDisposalCase
        form.proposedLocationAddress = state.homesteadForm.proposedLocationAddress
        form.proposedHomesteadArea = state.homesteadForm.proposedHomesteadArea
        form.proposedEastTo = state.homesteadForm.proposedEastTo
        form.proposedWestTo = state.homesteadForm.proposedWestTo
        form.proposedSouthTo = state.homesteadForm.proposedSouthTo
        form.proposedNorthTo = state.homesteadForm.proposedNorthTo
        form.proposedConstructionLandArea = state.homesteadForm.proposedConstructionLandArea
        form.proposedUnusedArea = state.homesteadForm.proposedUnusedArea
        form.proposedBuildingStorey = state.homesteadForm.proposedBuildingStorey
        form.proposedBuildingHeight = state.homesteadForm.proposedBuildingHeight
        form.proposedDesignType = state.homesteadForm.proposedDesignType
        form.architectureAtlasId = state.homesteadForm.architectureAtlasId
        form.isSeekNeighboursOpinion = state.homesteadForm.isSeekNeighboursOpinion
        form.proposedAgriculturalLandArea = state.homesteadForm.proposedAgriculturalLandArea
        form.proposedArableLand = state.homesteadForm.proposedArableLand
        form.proposedWoodlandArea = state.homesteadForm.proposedWoodlandArea
        form.proposedConstructionArea = state.homesteadForm.proposedConstructionArea
        form.keepArea = state.homesteadForm.keepArea
        form.neighboursOpinion = state.homesteadForm.neighboursOpinion
        form.otherDisposalCase = state.homesteadForm.otherDisposalCase
        form.proposedTown = state.homesteadForm.proposedTown
        form.proposedVillage = state.homesteadForm.proposedVillage
        if (form.proposedTown && form.proposedVillage) {
          fieldValue.value = form.proposedTown + '/' + form.proposedVillage
        }
      } else {
        state.homesteadForm = {}
      }
    }

    // 风貌图集预览
    const handlePreview = (imgList) => {
      const fullImages = imgList.map((v) => fileServerPrefix.value + v)
      ImagePreview({
        images: fullImages,
        showIndex: true,
        showIndicators: true,
        closeable: true,
      })
    }
    const handleSelect = (id) => {
      state.architectureAtlasId = id
    }
    //获取公示列表
    const getDataList = async () => {
      architectureAtlas(state.listQuery).then((res) => {
        const data = res.data
        state.architecturalStyleList = state.architecturalStyleList.concat(data.records)
        state.totalPage = data.total
        state.loading = false
        if (state.architecturalStyleList.length >= data.total) state.finished = true
      })
    }

    // 加载列表
    const onLoad = () => {
      if (!state.refreshing && state.architecturalStyleList.length < state.totalPage) {
        state.listQuery.pageNo = state.listQuery.pageNo + 1
      }
      if (state.refreshing) {
        state.architecturalStyleList = []
        state.refreshing = false
      }
      getDataList()
    }

    // 刷新列表
    const onRefresh = () => {
      state.refreshing = true
      state.finished = false
      state.loading = true
      state.listQuery.pageNo = 1
      onLoad()
    }

    const onSubmit = () => {
      saveLocal()
      const applyUserInfo = JSON.parse($localStorage.get('applyUserInfo'))
      const familyMemberList = JSON.parse($localStorage.get('familyMemberList'))
      const homesteadForm = JSON.parse($localStorage.get('homesteadForm'))
      let params = Object.assign({ isSubmit: '0', familyMemberList: familyMemberList }, applyUserInfo, homesteadForm)
      state.isCommit = true
      saveBuildApply(params)
        .then((res) => {
          if (res.code == 100) {
            Toast.success('保存成功')
            setTimeout(() => {
              router.push({ path: '/record-apply/record-list' })
            }, 500)
          }
          state.isCommit = false
        })
        .catch(() => {
          state.isCommit = false
        })
    }
    const goNext = () => {
      if (form.proposedDesignType === '2' && !form.architectureAtlasId) {
        Toast.fail(`请选择建筑风貌`)
        return
      }
      dataForm.value.validate().then(() => {
        saveLocal()
        router.push({ path: '/build-apply/build-info' })
      })
    }
    const goBack = () => {
      saveLocal()
      router.push({ path: '/build-apply/apply-info' })
    }

    // 修改级联选择
    const onChange = ({ value }) => {
      const index = cascadeOptions.value.findIndex(function (item) {
        return item.regionCode === value
      })
      if (index !== -1) {
        findByParentCode({
          level: 5,
          parentCode: value,
        }).then((res) => {
          cascadeOptions.value[index].children = res.body.list || []
          state.showPicker = true
        })
      }
    }
    // 全部选项选择完毕后，会触发 finish 事件
    const onFinish = ({ selectedOptions }) => {
      state.showPicker = false
      form.proposedTown = selectedOptions[0].regionCode
      if (selectedOptions.length > 1) {
        form.proposedVillage = selectedOptions[1].regionCode || ''
      }
      fieldValue.value = selectedOptions.map((option) => option.regionName).join('/')
    }
    const saveLocal = () => {
      state.homesteadForm.homesteadArea = form.homesteadArea
      state.homesteadForm.preCapitaHomesteadArea = form.preCapitaHomesteadArea
      state.homesteadForm.certOwnershipNo1 = form.certOwnershipNo1
      state.homesteadForm.constructionArea = form.constructionArea
      state.homesteadForm.preCapitaConstructionArea = form.preCapitaConstructionArea
      state.homesteadForm.certOwnershipNo2 = form.certOwnershipNo2
      state.homesteadForm.proposedLocationAddress = form.proposedLocationAddress
      state.homesteadForm.proposedHomesteadArea = form.proposedHomesteadArea
      state.homesteadForm.proposedEastTo = form.proposedEastTo
      state.homesteadForm.proposedWestTo = form.proposedWestTo
      state.homesteadForm.proposedSouthTo = form.proposedSouthTo
      state.homesteadForm.proposedNorthTo = form.proposedNorthTo
      state.homesteadForm.proposedConstructionLandArea = form.proposedConstructionLandArea
      state.homesteadForm.proposedBuildingStorey = form.proposedBuildingStorey
      state.homesteadForm.proposedBuildingHeight = form.proposedBuildingHeight
      state.homesteadForm.proposedDesignType = form.proposedDesignType
      state.homesteadForm.architectureAtlasId = form.architectureAtlasId
      state.homesteadForm.isSeekNeighboursOpinion = form.isSeekNeighboursOpinion
      state.homesteadForm.presentHomesteadDisposalCase = form.presentHomesteadDisposalCase
      state.homesteadForm.proposedUnusedArea = form.proposedUnusedArea
      state.homesteadForm.proposedAgriculturalLandArea = form.proposedAgriculturalLandArea
      state.homesteadForm.proposedArableLand = form.proposedArableLand
      state.homesteadForm.proposedWoodlandArea = form.proposedWoodlandArea
      state.homesteadForm.proposedConstructionArea = form.proposedConstructionArea
      state.homesteadForm.keepArea = form.keepArea
      state.homesteadForm.neighboursOpinion = form.neighboursOpinion
      state.homesteadForm.otherDisposalCase = form.otherDisposalCase
      state.homesteadForm.proposedTown = form.proposedTown
      state.homesteadForm.proposedVillage = form.proposedVillage
      $localStorage.set('homesteadForm', JSON.stringify(state.homesteadForm))
    }

    const cascadeOptions = computed(() => {
      return store.state.townOptions
    })
    const fileServerPrefix = computed(() => {
      return store.state.fileServerPrefix
    })
    return {
      form,
      fieldValue,
      options,
      dataForm,
      cascadeOptions,
      fileServerPrefix,
      ...toRefs(state),
      onSubmit,
      goNext,
      goBack,
      onFinish,
      onChange,
      handlePreview,
      onRefresh,
      onLoad,
      handleSelect,
    }
  },
}
</script>

<style lang="less" scoped>
@import '@/common/style/mixin';
.page {
  .btn-group {
    padding-bottom: 20px;
  }
}
.info-message {
  background: #ffffff;
  border-radius: 15px;
  margin-bottom: 20px;
  .info-title {
    padding: 15px;
    font-size: 16px;
    font-weight: bold;
    color: #2e3f6a;
    border-bottom: 1px solid #dee1eb;
  }
  .info-form {
    padding-bottom: 10px;
    .content {
      height: 300px;
      overflow: hidden;
      overflow-y: scroll;
      .img-num {
        margin-left: 10px;
      }
    }
    .van-cell-group--inset {
      margin: 0;
    }
  }
  .info-header {
    padding: 15px;
    display: flex;
    justify-content: space-between;
    .left {
      font-size: 18px;
      font-weight: bold;
      color: #2e3f6a;
    }
    .right {
      font-size: 16px;
      font-weight: 400;
      color: #3487f6;
    }
  }
  .info-user {
    padding-bottom: 20px;
  }
  .form-icon {
    margin-top: 5px;
  }
}
</style>